using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Windows.Forms;
using System.Reflection;
using System.IO;
using System.Drawing.Imaging;

namespace BingDownloader
{
    partial class MainForm : Form
    {
        System.Media.SoundPlayer _fadein = new System.Media.SoundPlayer(BingDownloader.Properties.Resources.Fadein);
        System.Media.SoundPlayer _fadeout = new System.Media.SoundPlayer(BingDownloader.Properties.Resources.Fadeout);
        
        int currentImage = 0;
        int numBingObjectsFound = 0;
        ImageForm imgForm = new ImageForm();
        Random rd = new Random();
        
        string directoryName, todayFile;

        public MainForm()
        {
            InitializeComponent();

            //this.labelInfo.Text = "This program is a open source and freeware. Feel free to distribute it.\r\nIf you are a developer looking for its code, head to http://bing.codeplex.com";
            this.labelProductName.Text = String.Format("{0} {1} \r\n{2}", AssemblyTitle, AssemblyVersion, AssemblyCopyright);
            _fadein.Play();
            timer1.Start();

            string directoryName = Environment.CurrentDirectory + @"\BingImages\";
            DateTime fileDate = DateTime.Now.AddHours(-7).ToUniversalTime();
            string todayFile = fileDate.Day.ToString() + "-" +
                               fileDate.Month.ToString() + "-" +
                               fileDate.Year.ToString() + ".jpg";

            try
            {

                Directory.CreateDirectory(directoryName);
            }
            catch (UnauthorizedAccessException)
            {
                MessageBox.Show("Cannot create BingImages folder, Try running BingDownloader from a location where you have write access. This is usually your Documents/Pictures folder rather than Program Files");
                return;
            }

            ToolTip tt = new ToolTip();
            tt.SetToolTip(bingPictureBox, "Click to enlarge it");
        }

        #region Assembly Attribute Accessors

        public string AssemblyTitle
        {
            get
            {
                // Get all Title attributes on this assembly
                object[] attributes = Assembly.GetExecutingAssembly().GetCustomAttributes(typeof(AssemblyTitleAttribute), false);
                // If there is at least one Title attribute
                if (attributes.Length > 0)
                {
                    // Select the first one
                    AssemblyTitleAttribute titleAttribute = (AssemblyTitleAttribute)attributes[0];
                    // If it is not an empty string, return it
                    if (titleAttribute.Title != "")
                        return titleAttribute.Title;
                }
                // If there was no Title attribute, or if the Title attribute was the empty string, return the .exe name
                return System.IO.Path.GetFileNameWithoutExtension(Assembly.GetExecutingAssembly().CodeBase);
            }
        }

        public string AssemblyVersion
        {
            get
            {
                return Assembly.GetExecutingAssembly().GetName().Version.ToString();
            }
        }

        public string AssemblyDescription
        {
            get
            {
                // Get all Description attributes on this assembly
                object[] attributes = Assembly.GetExecutingAssembly().GetCustomAttributes(typeof(AssemblyDescriptionAttribute), false);
                // If there aren't any Description attributes, return an empty string
                if (attributes.Length == 0)
                    return "";
                // If there is a Description attribute, return its value
                return ((AssemblyDescriptionAttribute)attributes[0]).Description;
            }
        }

        public string AssemblyProduct
        {
            get
            {
                // Get all Product attributes on this assembly
                object[] attributes = Assembly.GetExecutingAssembly().GetCustomAttributes(typeof(AssemblyProductAttribute), false);
                // If there aren't any Product attributes, return an empty string
                if (attributes.Length == 0)
                    return "";
                // If there is a Product attribute, return its value
                return ((AssemblyProductAttribute)attributes[0]).Product;
            }
        }

        public string AssemblyCopyright
        {
            get
            {
                // Get all Copyright attributes on this assembly
                object[] attributes = Assembly.GetExecutingAssembly().GetCustomAttributes(typeof(AssemblyCopyrightAttribute), false);
                // If there aren't any Copyright attributes, return an empty string
                if (attributes.Length == 0)
                    return "";
                // If there is a Copyright attribute, return its value
                return ((AssemblyCopyrightAttribute)attributes[0]).Copyright;
            }
        }

        public string AssemblyCompany
        {
            get
            {
                // Get all Company attributes on this assembly
                object[] attributes = Assembly.GetExecutingAssembly().GetCustomAttributes(typeof(AssemblyCompanyAttribute), false);
                // If there aren't any Company attributes, return an empty string
                if (attributes.Length == 0)
                    return "";
                // If there is a Company attribute, return its value
                return ((AssemblyCompanyAttribute)attributes[0]).Company;
            }
        }
        #endregion

        private void timer1_Tick(object sender, EventArgs e)
        {
            if (this.Opacity > 0.8)
            {
                timer1.Stop();
            }
            else
            {
                this.Opacity += 0.1;
            }
        }
        protected override void WndProc(ref Message m)
        {
            const int WmNcHitTest = 0x84;
            const int WmNCDoubleClick = 0x00A3;
            const int HtClient = 1;
            const int HtCaption = 2;

            if (m.Msg == WmNCDoubleClick)
                m.Result = new IntPtr(HtClient);
            else if (m.Msg == WmNcHitTest)
                m.Result = new IntPtr(HtCaption);
            else
                base.WndProc(ref m);
        }
        private void MainForm_FormClosing(object sender, FormClosingEventArgs e)
        {
            _fadeout.Play();
            for (; this.Opacity > 0.1; )
            {
                this.Opacity -= 0.1;
                System.Threading.Thread.Sleep(25);
            }
        }

        private void buttonClose_MouseHover(object sender, EventArgs e)
        {
            buttonClose.Image = global::BingDownloader.Properties.Resources.closebright;
        }

        private void buttonClose_MouseLeave(object sender, EventArgs e)
        {
            buttonClose.Image = global::BingDownloader.Properties.Resources.closenormal;
        }

        private void buttonClose_Click(object sender, EventArgs e)
        {
            BingHelper.StopGettingBingImages();            
            this.Close();
        }

        private void linkLabel1_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            System.Diagnostics.Process.Start("http://mugunthkumar.com");
        }

        private void MainForm_Load(object sender, EventArgs e)
        {
            labelCountry.Text = "Loading...";
            labelImageName.Text = "";
            hotlink1.Text = hotlink2.Text = hotlink3.Text = hotlink4.Text = "";
            this.SetBounds(this.Bounds.X, this.Bounds.Y, 300, 165);

            BingHelper.ObjectFound += this.ObjectFound;            
            BingHelper.BeginGettingBingImages();

            directoryName = Environment.CurrentDirectory + @"\BingImages\";
            DateTime fileDate = DateTime.Now.AddHours(-7).ToUniversalTime();
            todayFile = fileDate.Day.ToString() + "-" +
                               fileDate.Month.ToString() + "-" +
                               fileDate.Year.ToString() + ".jpg";

            try
            {

                Directory.CreateDirectory(directoryName);
            }
            catch (UnauthorizedAccessException)
            {
                MessageBox.Show("Cannot create BingImages folder, Try running BingDownloader from a location where you have write access. This is usually your Documents/Pictures folder rather than Program Files");
                return;
            }

        }

        public delegate void ProgValDelegate(int progress);


        private void setProgVal(int progress)
        {
            progressBarMain.Value = progress;
            if (progress == 100) progressBarMain.Visible = false;
        }

        private void ObjectFound(BingObject bo)
        {
            string strFileName = directoryName + bo.CountryCode + "_" + todayFile;
            try
            {
                bo.Image.Save(strFileName, ImageFormat.Jpeg);
            }
            catch (System.Runtime.InteropServices.ExternalException)
            {
                MessageBox.Show("Some issue with the file name. :-(" + strFileName);
            }          

            object[] parameters = new object[1];
            numBingObjectsFound++;
            parameters[0] = Convert.ToInt32(((double)numBingObjectsFound / (double)BingHelper.BingImagesCount)*100.0);
            progressBarMain.BeginInvoke(new ProgValDelegate(setProgVal), parameters);            
        }

        private void timerPicRotate_Tick(object sender, EventArgs e)
        {
            if (numBingObjectsFound == 0) return;
            if (this.Width < 500)
                MakeFormBigger();            
            if (currentImage >= numBingObjectsFound) currentImage = 0;

            BingObject bo = BingHelper.GetBingObject(currentImage);
            bingPictureBox.BackgroundImage = bo.Image as Image;
            imgForm.BackgroundImage = bingPictureBox.BackgroundImage;

            labelCountry.Text = bo.CountryName;
            labelImageName.Text = bo.ImageName;
           
            hotlink1.Text = bo.GetHotLinkDescription(1);
            hotlink2.Text = bo.GetHotLinkDescription(2);
            hotlink3.Text = bo.GetHotLinkDescription(3);
            hotlink4.Text = bo.GetHotLinkDescription(4);           
            currentImage++;
            
            this.BackColor = Color.FromArgb(
                127 + (int)(rd.NextDouble() * 127),
                127 +(int)(rd.NextDouble() * 127),
                127 +(int)(rd.NextDouble() * 127));

            buttonClose.BackColor = this.BackColor;
            this.Invalidate();
        }

        private void MakeFormBigger()
        {
            this.bingPictureBox.Visible = false;
            for (; ; )
            {
                this.Width += 3; this.Height++;
                if (this.Width >= this.MaximumSize.Width) this.Width = this.MaximumSize.Width;
                if (this.Height >= this.MaximumSize.Height) this.Height = this.MaximumSize.Height;

                if (this.Width == this.MaximumSize.Width && this.Height == this.MaximumSize.Height) break;

                System.Threading.Thread.Sleep(1);
            }

            this.bingPictureBox.Visible = true;
        }

        private void hotlink1_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            BingObject bo = BingHelper.GetBingObject(currentImage-1);
            string url = bo.GetHotLinkURL(1);
            System.Diagnostics.Process.Start(url);
        }

        private void hotlink2_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            BingObject bo = BingHelper.GetBingObject(currentImage-1);
            string url = bo.GetHotLinkURL(2);
            System.Diagnostics.Process.Start(url);
        }

        private void hotlink3_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            BingObject bo = BingHelper.GetBingObject(currentImage-1);
            string url = bo.GetHotLinkURL(3);
            System.Diagnostics.Process.Start(url);
        }

        private void hotlink4_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            BingObject bo = BingHelper.GetBingObject(currentImage-1);
            string url = bo.GetHotLinkURL(4);
            System.Diagnostics.Process.Start(url);
        }

        private void bingPictureBox_Click(object sender, EventArgs e)
        {
            if (numBingObjectsFound == 0) return;
            if (currentImage > numBingObjectsFound) currentImage = 1;

            BingObject bo = BingHelper.GetBingObject(currentImage-1);
            ImageForm imgForm = new ImageForm();
            imgForm.Width = bo.Image.Width;
            imgForm.Height = bo.Image.Height;
            imgForm.BackgroundImage = bo.Image;
            imgForm.Show();

        }
    }
}
